package server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.handle.InitHandle;
import support.RpcContext;
import util.BannerUtil;
import util.NetWorkUtil;

public class CoreServer {
    ServerBootstrap serverBootstrap;
    NioEventLoopGroup boss;
    NioEventLoopGroup worke;
    ChannelFuture future;

    static boolean flag=false;

    static int port=3306;

    static String benHostAddr = NetWorkUtil.getIpAddress();

    static volatile CoreServer coreServer;

    static Logger logger = LoggerFactory.getLogger(CoreServer.class);

    private CoreServer() throws Exception {
        serverBootstrap = new ServerBootstrap();
        boss = new NioEventLoopGroup(2);
        worke = new NioEventLoopGroup(8);
        serverBootstrap = serverBootstrap.group(boss, worke).channel(NioServerSocketChannel.class).childHandler(new InitHandle());
        try {
            future = serverBootstrap.bind("0.0.0.0", port).sync();
            BannerUtil.showBanner(CoreServer.class);
        }catch (Exception e){
            boss.shutdownGracefully();
            worke.shutdownGracefully();
            throw e;
        }
        logger.info("服务在{}端口启动成功",port);

//        future.addListener(li->{
//            if(li.isSuccess()){
//                logger.info("启动成功");
//            }else {
//                logger.info("启动失败");
//
//            }
//        });

    }

    static public CoreServer getInstance(int p){

        if(!flag){
            synchronized (CoreServer.class){
                if(!flag){
                    while (true){
                        try {
                            port = p;
                            coreServer = new CoreServer();
                            flag = true;
                            break;
                        }catch (Exception e){
                            e.printStackTrace();
                            logger.info("端口被占用，正在以{}端口启动...",port+1);
                            port++;
                            p++;
                        }
                    }

                }
            }
        }
        return coreServer;

    }
}
